package com.lsh.ofc.proxy.service;

import com.alibaba.fastjson.JSON;
import com.lsh.ofc.proxy.util.HttpClientUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.http.Header;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class OpenApiServiceProxy {

    private final static Logger logger = LoggerFactory.getLogger(OpenApiServiceProxy.class);

    @Value("${open.api.host}")
    private String openApiHost;

    @Value("${path.of.create.external.coordination.so}")
    private String createSalesOrderPath;

    @Value("${path.of.withdraw.external.coordination.so}")
    private String withdrawSalesOrderPath;

    public boolean createSalesOrder(Map<String, Object> request, Map<String, Object> headers) {
        String url = this.openApiHost + createSalesOrderPath;
        return post(url, request, headers);
    }

    public boolean withdrawSalesOrder(Map<String, Object> request, Map<String, Object> headers) {
        String url = this.openApiHost + withdrawSalesOrderPath;
        return post(url, request, headers);
    }

    private boolean post(String url, Map<String, Object> request, Map<String, Object> headers) {
        logger.info("call open api url: " + url + ", headers: " + JSON.toJSONString(headers) + ", request body: " + JSON.toJSONString(request));
        try {
            StringEntity stringEntity = new StringEntity(JSON.toJSONString(request), "UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");

            String content = HttpClientUtils.post(url, stringEntity, headers(headers)).getData();
            logger.info("call open api url: " + url + ", response body: " + content);

            int ret = JSON.parseObject(content).getIntValue("ret");
            return ret == 0;
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
        }
        return false;
    }

    private Header[] headers(Map<String, Object> input) {
        List<Header> headers = new ArrayList<>(input.size());
        if (MapUtils.isNotEmpty(input)) {
            for (Map.Entry<String, Object> entry : input.entrySet()) {
                headers.add(new BasicHeader(entry.getKey(), String.valueOf(entry.getValue())));
            }
        }
        return headers.toArray(new Header[0]);
    }
}
